# -*- coding: utf-8 -*-

import os
import time
import hashlib
import threading
import urllib
import commands
import wx

class Spirit(threading.Thread):
    window_ref = None
    _hash = None
# http://www.dmi.unict.it/~zamboni/esitoanalisi3.pdf

    def __init__(self, window_ref, settings):
        threading.Thread.__init__(self)
        self._event = threading.Event()
        self._pauseevent = threading.Event()
        self._exitevent = threading.Event()
        self._timer = int(settings["timer"])
        self._url = settings["url"]
        Spirit.window_ref = window_ref
    
    def update_settings(self, settings):
        if self._url == settings["url"]:
            self._timer = int(settings["timer"])
        else:
            self._url = settings["url"]
            self._timer = int(settings["timer"])
            self._hash = self.get_hash()
            Spirit.window_ref.color_change(self)
    
    def set_hash(self, hash_):
        self._hash = hash_
    
    def get_hash(self):
        try:
            file_ = urllib.urlopen(self._url)
        except IOError:
            print "Indirizzo non trovato..."
            return None
        data = file_.read()
        file_.close()
        hash_ = hashlib.md5(data)
        
        return hash_.hexdigest()
    
    def open_url(self, url):
        if(wx.GetOsDescription().startswith("Mac")):
            commands.getoutput("open /Applications/Safari.app " + url)
        elif(wx.GetOsDescription().startswith("Windows")):
            dialog = wx.MessageDialog(Spirit.window_ref, "Passa a Linux, fidati, è meglio!!", "Consiglio", style=wx.OK|wx.ICON_EXCLAMATION)
            dialog.ShowModal()
            dialog.Destroy
        else:
            commands.getoutput("firefox " + url)
    
    def pause(self):
        self._pauseevent.clear() # mette a false _pauseevent
        self._event.set() # mette a true _event
    
    def restart(self):
        self._event.clear() # mette a false _event
        self._pauseevent.set() # mette a true _pauseevent
    
    def terminate(self):
        self._exitevent.set()
        self._pauseevent.set()
        self._event.set()
        print self._exitevent.is_set(), self._pauseevent.is_set(), self._event.is_set()
    
    def run(self):
        self._pauseevent.set()
        while not self._exitevent.is_set():
            print "Controllo", self._url, "\n", self._hash
            if self._hash:
                new_hash = self.get_hash()
                if new_hash != self._hash:
                    Spirit.window_ref.color_change(self, '#ff6633')
                    self.time_ = time.localtime()
                    Spirit.window_ref.set_time(self, self.time_)
                    print "Yeah!!\n\t%s -> %s" % (self._hash, new_hash)
                    dialog = wx.MessageDialog(Spirit.window_ref, "Si e' verificato un cambiamento!!\n\nVuoi aprire la pagina nel browser?", "%s" % self._url, style=wx.YES_NO|wx.ICON_INFORMATION)
                    choice = dialog.ShowModal()
                    dialog.Destroy
                    self._hash = new_hash
                    self.pause()
                    print "In pausa dopo il cambiamento"
                    if choice == wx.ID_YES:
                        self.open_url(self._url)
            else:
                self._hash = self.get_hash()
                self.time_ = time.localtime()
                Spirit.window_ref.set_time(self, self.time_)
            self._event.wait(self._timer)
            self._pauseevent.wait() # si blocca finche' event e' false
    
